<template>
  <div>
    <div class="goods fixed oh flex-def">
      <div class="menu-wrapper"
           ref="menuWrapper">
        <ul>
          <li class="menu-item f0 border-1px-bottom menuHooks"
              v-for="(good, index) in goods"
              :key="index"
              :class="{active:currentIndex===index}"
              @click="selectMenu(index,$event)">
            <div class="row f18">
              <span class="icon inline-block"
                    :class="classMap[good.type]"
                    v-show="good.type > 0">
              </span>
              <strong class="f12 fw300 poi">{{ good.name }}</strong>
            </div>
          </li>
        </ul>
      </div>
      <div class="foods-wrapper"
           ref="foodsWrapper">
        <ul>
          <li class="foods-list foodsHook"
              v-for="(good, index) in goods"
              :key="index">
            <h3 class="foods-item-title f12 fw400 relative">{{ good.name }}</h3>
            <ul>
              <li class="foods-item flex-def border-1px-bottom"
                  v-for="(food, foodIndex) in good.foods"
                  :key="foodIndex"
                  @click="foodDetail(food,$event)">
                <div class="icon">
                  <img :src="food.icon"
                       alt=""
                       width="57"
                       height="57" />
                </div>
                <div class="content">
                  <h4 class="foods-name f14 fw400">{{ food.name }}</h4>
                  <p class="description f12">{{ food.description }}</p>
                  <p class="extra f12 fw300">
                    <span class="sellCount">月售{{ food.sellCount }}份</span>
                    <strong>好评率{{ food.rating }}%</strong>
                  </p>
                  <div class="price flex-def">
                    <p class="inline-block fw500 f14">
                      ¥<span class="newPrice fw600 f18">{{ food.price }}</span>
                    </p>
                    <p class="inline-block fw400 f12"
                       v-show="food.oldPrice">
                      ¥<span class="oldPrice f13 fw300">{{ food.oldPrice }}</span>
                    </p>
                  </div>
                  <div class="controlCart-wrapper absolute">
                    <control-cart :food="food"
                                  @add="onAdd">
                    </control-cart>
                  </div>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
    <food :food="selectedFood"
          ref="food"
          @add="onAdd"></food>
    <shop-cart :min-price="seller.minPrice"
               :delivery-price="seller.deliveryPrice"
               :select-foods="selectFoods"
               ref="shopCart">
    </shop-cart>
  </div>
</template>

<script>
import { getGoods } from 'api';
import { mixin, seller } from 'mixin';
import { timeout } from 'common/js/utils';
import { saveToLocal, loadFromLocal } from 'common/js/storage';
import BScroll from 'better-scroll';
import ShopCart from 'components/ShopCart/ShopCart';
import ControlCart from 'components/ControlCart/ControlCart';
import Food from 'views/Food';

export default {
  'mixins': [mixin, seller],
  'name': 'goods',
  data() {
    return { 'goods': [], 'heightCalcu': [], 'scrollY': 0, 'initGoods': [], 'selectedFood': {} };
  },
  'components': { ShopCart, ControlCart, Food },
  async created() {
    // data数据已经初始化，但是DOM结构渲染完成，组件没有加载
    this._getFoods({ 'id': this.seller.id });
    await timeout(400);
    this._initScroll();
    this._calcuHeight();
  },
  mounted() {
    // DOM渲染完成，组件挂载完成
  },
  'computed': {
    currentIndex() {
      const ele = this.$refs.menuWrapper.getElementsByClassName('menuHooks');
      if (this.heightCalcu.length <= 2) return;
      for (let index = 0; index < this.heightCalcu.length; index++) {
        let height1 = this.heightCalcu[index];
        let height2 = this.heightCalcu[index + 1];
        if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
          this.menuWrapper.scrollToElement(ele[index], 300);
          return index;
        }
      }
      return 0;
    },
    selectFoods() {
      const selectFoods = [];
      this.goods.forEach(ele => {
        ele.foods.forEach(item => {
          if (item.count) selectFoods.push(item);
        });
      });
      setTimeout(() => {
        saveToLocal(this.seller.id, 'goods', this.goods);
      }, 100);
      return selectFoods;
    }
  },
  'methods': {
    foodDetail(food, event) {
      if (!event._constructed) return;
      this.selectedFood = food;
      this.$refs.food.show();
    },
    onAdd(target) {
      setTimeout(() => {
        this.$refs.shopCart.drop(target);
      }, 150);
    },
    selectMenu(index, event) {
      if (!event._constructed) return;
      const ele = this.$refs.foodsWrapper.getElementsByClassName('foodsHook');
      this.foodsWrapper.scrollToElement(ele[index], 500);
    },
    async _getFoods(ID) {
      let goods = await getGoods(ID);
      const loadGood = loadFromLocal(this.seller.id, 'goods', goods);
      if (loadGood.length === 0) this.goods = goods;
      else this.goods = loadGood;
    },
    _initScroll() {
      this.menuWrapper = new BScroll(this.$refs.menuWrapper, {
        'click': true,
        'scrollX': false,
        'scrollY': true
      });
      this.foodsWrapper = new BScroll(this.$refs.foodsWrapper, {
        'click': true,
        'probeType': 3,
        'scrollX': false,
        'scrollY': true
      });
      this.foodsWrapper.on('scroll', pos => {
        this.scrollY = Math.abs(Math.round(pos.y));
      });
    },
    _calcuHeight() {
      let statistics = this.$refs.foodsWrapper.getElementsByClassName('foodsHook');
      let height = 0;
      this.heightCalcu.push(height);
      for (let index = 0; index < statistics.length; index++) {
        height += statistics[index].clientHeight;
        this.heightCalcu.push(height);
      }
    }
  },
  'watch': {},
  // beforeDestroy() {
  //   if (this.selectFoods.length > 0) saveToLocal(this.seller.id, 'goods', this.goods);
  // },
  // destroyed() {
  //   window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e));
  // },
  deactivated() {
    saveToLocal(this.seller.id, 'goods', this.goods);
  }
};
</script>

<style lang="stylus" rel="stylesheet/stylus">
@import '~common/stylus/mixin'
.goods
  top 174px
  bottom 46px
  left 0
  width 100%
  .menu-wrapper
    flex 0 0 80px
    width 80px
    background-color #f3f5f7
    .menu-item
      display flex
      align-items center
      height 56px
      line-height 1.2
      padding(0, 10, 0, 10)
      border-1px-bottom(rgba(7, 17, 27, 0.15))
      &.active
        background-color #fff
        margin-top -1px
        z-index 10
        border-none()
      &:last-child
        border-none()
      .row
        line-height 14px
        strong
          color rgb(102, 102, 102)
          vertical-align top
        .icon
          margin-right 2px
          &.decrease
            bg-image('decrease_3', 12, 12)
          &.discount
            bg-image('discount_3', 12, 12)
          &.guarantee
            bg-image('guarantee_3', 12, 12)
          &.invoice
            bg-image('invoice_3', 12, 12)
          &.special
            bg-image('special_3', 12, 12)
  .foods-wrapper
    flex 1
    .foods-item-title
      text-indent 14px
      height 26px
      line-height 26px
      background-color #f3f5f7
      color rgb(147, 153, 157)
      &:after
        content ''
        width 0
        // display inline-block
        position absolute
        top 0
        left 0
        height 26px
        border-left 2px solid #d9dde1
        box-shadow 2px 0px 1px 1px #d9dde1
    .foods-item
      margin(18, 18, 18, 18)
      padding-bottom 18px
      border-1px-bottom(rgba(7, 17, 27, 0.2))
      &:last-child
        border-none()
      .icon
        flex 0 0 57px
        width 57px
        margin-right 10px
        overflow hidden
      .content
        flex 1
        .foods-name
          color rgb(7, 17, 27)
        .description, .extra, .price
          margin-top 8px
          color rgb(147, 153, 157)
        .extra
          strong
            margin-left 12px
        .price
          color rgb(240, 20, 20)
          align-items center
          span
            margin-left 2px
          & > p:nth-child(2)
            margin-left 8px
            text-decoration line-through
            color rgb(147, 153, 157)
            .oldPrice
              vertical-align middle
        .controlCart-wrapper
          bottom 10px
          right 0
</style>
